#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    table=P_RSS;
    repoModel=new QStringListModel(this);
    ui->reposView->setModel(repoModel);

    itemModel=new QStringListModel(this);
    ui->listView->setModel(itemModel);

    updateRepos();
    startReceiver();
}

Widget::~Widget()
{
    stopReceiver();
    delete ui;
}

void Widget::updateRepos()
{
    QStringList items=sp_getItems("label",table);
    repoModel->setStringList(items);
}

void Widget::startReceiver()
{
    receiver=new BaseHttpReceiver;
    connect(receiver,&BaseHttpReceiver::received,
            this,&Widget::onReceived);
    connect(this,&Widget::get,
            receiver,&BaseHttpReceiver::httpGet);
    connect(&recvThread,&QThread::finished,
            receiver,&QObject::deleteLater);
    receiver->moveToThread(&recvThread);
    recvThread.start();
}

void Widget::stopReceiver()
{
    recvThread.quit();
    recvThread.wait();
}

void Widget::onReceived(const QByteArray &data)
{
    if(url.isEmpty())
        return;

    QString fileName=QUrl(url).fileName();
    QString suffix=QFileInfo(fileName).suffix();
    if(suffix == "xml")
    {
        itemMap=readRSS(data);
        itemModel->setStringList(itemMap.keys());
    }
}

void Widget::on_btn_paste_clicked()
{
    QString url=qApp->clipboard()->text();
    if(url.isEmpty())
        return;

    ui->url->setText(url);
}

void Widget::on_btn_submit_clicked()
{
    url=ui->url->text().trimmed();
    if(url.isEmpty())
        return;

    emit get(url);
}

void Widget::on_listView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        QString title=index.data().toString();
        if(itemMap.contains(title))
        {
            QString link=itemMap.value(title);
            QDesktopServices::openUrl(QUrl(link));
        }
    }
}

void Widget::on_reposView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        QString title=index.data().toString();
        if(title.isEmpty())
            return;

        url=sp_getItem("detail",table,"label",title).toString();
        if(!url.isEmpty())
            emit get(url);
    }
}
